<?php
declare (strict_types = 1);

namespace app\model;

use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;

/**
 * @mixin Model
 */
class ProductUnits extends Model
{
    /**
     * 获取所有单位
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function getAllUnits(): array|Collection
    {
        return $this->select();
    }

    /**
     * 批量创建单位
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function createUnit($payload, $data): array
    {
        //检查是否存在重名
        if($this->whereIn('name',$payload)->find()){
            return modelResponse(403,'单位名重复');
        }
        try {
            $this->saveAll($data);
            return modelResponse(200,'单位添加成功');
        }catch (\Exception $e){
            return modelResponse($e->getCode(), $e->getMessage());
        }
    }

    /**
     * 更新单位名称
     * @param $id
     * @param $data
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function updateUnit($id,$data): array
    {
        //检测是否和其他的名称重复
        if ($this->where('name', $data['name'])->where('id', '<>', $id)->find()) {
            return modelResponse(403, '单位名称重复');
        }
        try {
            $this->where('id', $id)->update($data);
            return modelResponse(200,'单位名称更新成功');
        }catch (\Exception $e){
            return modelResponse($e->getCode(), $e->getMessage());
        }
    }

    public function deleteUnit(int $id): array
    {
        try {
            $this->where('id', $id)->delete();
            return modelResponse(200, '单位名称删除成功');
        }catch (\Exception $e){
            return modelResponse(400, $e->getMessage());
        }
    }
}
